package com.mathmodeling.controller;

import com.mathmodeling.dto.ApiResponse;
import com.mathmodeling.entity.Score;
import com.mathmodeling.entity.Work;
import com.mathmodeling.entity.Team;
import com.mathmodeling.entity.Topic;
import com.mathmodeling.repository.ScoreRepository;
import com.mathmodeling.repository.WorkRepository;
import com.mathmodeling.repository.TeamRepository;
import com.mathmodeling.repository.TopicRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/teachers")
public class TeacherController {
    
    @Autowired
    private WorkRepository workRepository;
    
    @Autowired
    private ScoreRepository scoreRepository;
    
    @Autowired
    private TeamRepository teamRepository;
    
    @Autowired
    private TopicRepository topicRepository;
    
    @Value("${file.upload.path}")
    private String uploadPath;
    
    /**
     * 获取待评分作品列表 - 严格按照API文档响应格式
     */
    @GetMapping("/works")
    public ApiResponse<List<WorkListResponse>> getWorks(@RequestParam String contestId) {
        try {
            // 验证参数
            if (contestId == null || contestId.trim().isEmpty()) {
                return ApiResponse.error(400, "竞赛ID不能为空");
            }
            
            List<Work> works = workRepository.findByContestId(contestId);
            
            // 转换为API文档要求的响应格式
            List<WorkListResponse> responses = works.stream()
                    .map(work -> {
                        WorkListResponse response = new WorkListResponse();
                        response.setWorkId(work.getId());
                        response.setTeamId(work.getTeamId());
                        
                        // 获取团队信息
                        Team team = teamRepository.findById(work.getTeamId()).orElse(null);
                        if (team != null) {
                            response.setTeamName(team.getName());
                        }
                        
                        // 获取题目信息
                        Topic topic = topicRepository.findById(work.getTopicId()).orElse(null);
                        if (topic != null) {
                            response.setTopic(topic.getName());
                        }
                        
                        response.setThesisName(work.getAutoName() + ".pdf");
                        
                        return response;
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            return ApiResponse.success("获取成功", responses);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取作品列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取作品论文（用于评分查看）- 严格按照API文档规范
     */
    @GetMapping("/works/{workId}/thesis")
    public ResponseEntity<Resource> downloadThesis(@PathVariable String workId) {
        try {
            // 验证参数
            if (workId == null || workId.trim().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            
            // 查找作品
            Work work = workRepository.findById(workId)
                    .orElseThrow(() -> new RuntimeException("作品不存在"));
            
            // 构建文件路径
            Path filePath = Paths.get(work.getThesisPath());
            Resource resource = new UrlResource(filePath.toUri());
            
            // 检查文件是否存在且可读
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_PDF)
                        .header(HttpHeaders.CONTENT_DISPOSITION, 
                                "inline; filename=\"" + work.getAutoName() + ".pdf\"")
                        .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
                        .header(HttpHeaders.PRAGMA, "no-cache")
                        .header(HttpHeaders.EXPIRES, "0")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 下载支撑材料（审核用）- 严格按照API文档规范
     */
    @GetMapping("/works/{workId}/support")
    public ResponseEntity<Resource> downloadSupport(@PathVariable String workId) {
        try {
            // 验证参数
            if (workId == null || workId.trim().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            
            // 查找作品
            Work work = workRepository.findById(workId)
                    .orElseThrow(() -> new RuntimeException("作品不存在"));
            
            // 构建文件路径
            Path filePath = Paths.get(work.getSupportPath());
            Resource resource = new UrlResource(filePath.toUri());
            
            // 检查文件是否存在且可读
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .header(HttpHeaders.CONTENT_DISPOSITION, 
                                "attachment; filename=\"" + work.getAutoName() + ".rar\"")
                        .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
                        .header(HttpHeaders.PRAGMA, "no-cache")
                        .header(HttpHeaders.EXPIRES, "0")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 提交评分 - 严格按照API文档规范
     */
    @PostMapping("/works/{workId}/score")
    public ApiResponse<String> submitScore(@PathVariable String workId, 
                                         @RequestBody ScoreRequest request) {
        try {
            // 验证参数
            if (workId == null || workId.trim().isEmpty()) {
                return ApiResponse.error(400, "作品ID不能为空");
            }
            
            if (request == null) {
                return ApiResponse.error(400, "请求体不能为空");
            }
            
            if (request.getFinalScore() == null) {
                return ApiResponse.error(400, "最终分数不能为空");
            }
            
            // 验证分数范围
            if (request.getFinalScore() < 0 || request.getFinalScore() > 100) {
                return ApiResponse.error(400, "分数必须在0-100之间");
            }
            
            // 验证作品是否存在
            Work work = workRepository.findById(workId)
                    .orElseThrow(() -> new RuntimeException("作品不存在"));
            
            // 检查是否已经评分过
            if (scoreRepository.existsByWorkId(workId)) {
                return ApiResponse.error(400, "该作品已经评分过了");
            }
            
            // 创建评分记录
            Score score = new Score();
            score.setWorkId(workId);
            score.setValue(request.getFinalScore());
            score.setComment(""); // 根据API文档，不包含comment字段
            score.setScoredAt(LocalDateTime.now());
            
            scoreRepository.save(score);
            
            return ApiResponse.success("评分提交成功");
            
        } catch (Exception e) {
            return ApiResponse.error(500, "评分提交失败: " + e.getMessage());
        }
    }
    
    // 响应类
    public static class WorkListResponse {
        private String workId;
        private String teamId;
        private String teamName;
        private String topic;
        private String thesisName;
        
        // Getters and Setters
        public String getWorkId() { return workId; }
        public void setWorkId(String workId) { this.workId = workId; }
        
        public String getTeamId() { return teamId; }
        public void setTeamId(String teamId) { this.teamId = teamId; }
        
        public String getTeamName() { return teamName; }
        public void setTeamName(String teamName) { this.teamName = teamName; }
        
        public String getTopic() { return topic; }
        public void setTopic(String topic) { this.topic = topic; }
        
        public String getThesisName() { return thesisName; }
        public void setThesisName(String thesisName) { this.thesisName = thesisName; }
    }
    
    public static class ScoreRequest {
        private Integer finalScore;
        
        // Getters and Setters
        public Integer getFinalScore() { return finalScore; }
        public void setFinalScore(Integer finalScore) { this.finalScore = finalScore; }
    }
} 